<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable
                   size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告位置" prop="place">
        <el-select v-model="queryParams.place" placeholder="请选择广告位置" clearable size="small">
          <el-option
            v-for="dict in placeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['server:advertisement:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['server:advertisement:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['server:advertisement:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="advertisementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" prop="advertisementId" key="advertisementId"
                       v-if="columns[0].visible"/>
      <el-table-column label="封面图片" align="center" prop="imgSrc" :show-overflow-tooltip='true' key="imgSrc"
                       v-if="columns[1].visible">
        <template slot-scope="scope">
          <div
            style="width: 90%;height: 120px;display:flex;align-items:center; justify-content:center; border: dashed darkgrey 1px">
            <el-image v-if="scope.row.imgSrc != ''" style="width: auto;  height: auto" :src="scope.row.imgSrc"
                      :preview-src-list="srcList"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="广告链接地址" align="center" prop="url" :show-overflow-tooltip='true' key="url"
                       v-if="columns[2].visible"/>
      <el-table-column label="广告简述" align="center" prop="sketch" :show-overflow-tooltip='true' key="sketch"
                       v-if="columns[3].visible"/>
      <el-table-column label="排序" align="center" prop="sort" :show-overflow-tooltip='true' key="sort"
                       v-if="columns[4].visible"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" :show-overflow-tooltip='true'
                       key="status" v-if="columns[5].visible"/>
      <el-table-column label="广告位置" align="center" prop="place" :formatter="placeFormat" :show-overflow-tooltip='true'
                       key="place" v-if="columns[6].visible"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip='true' key="remark"
                       v-if="columns[7].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['server:advertisement:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['server:advertisement:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运营管理广告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="封面图片" prop="imgSrc">
          <el-upload
            v-if="form.imgSrc"
            ref="upload"
            action=""
            :show-file-list="false"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG"
            :auto-upload="false"
            :on-change="getFile">
            <img :src="form.imgSrc" style="width: 148px;height: 148px;border-radius: 6px">
            <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一张jpg/png图片，且不超过500kb</div>
          </el-upload>
          <el-upload
            v-else
            ref="upload"
            action=""
            :show-file-list="true"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG"
            :auto-upload="false"
            :on-change="getFile">
            <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一张jpg/png图片，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入广告链接地址"/>
        </el-form-item>
        <el-form-item label="广告简述" prop="sketch">
          <el-input v-model="form.sketch" placeholder="请输入广告简述" maxlength="200"/>
        </el-form-item>
        <el-form-item label="展示周期" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            size="small"
            style="width: 380px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="排序" prop="sort">-->
        <!--          <el-input v-model="form.sort" type="number" placeholder="请输入排序"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择广告状态" style="width: 380px">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告位置" prop="place">
          <el-select v-model="form.place" placeholder="请选择广告位置" style="width: 380px">
            <el-option
              v-for="dict in placeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="30"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAdvertisement,
  getAdvertisement,
  delAdvertisement,
  addAdvertisement,
  updateAdvertisement,
  exportAdvertisement
} from '@/api/server/operate/advertisement'
import {parseTime} from "../../../utils/project";

export default {
  name: 'Advertisement',
  components: {},
  data() {
    return {
      //预览图片列表
      srcList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运营管理广告表格数据
      advertisementList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      statusOptions: [],
      placeOptions: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        url: null,
        sketch: null,
        sort: null,
        status: null,
        place: null,
        dateRange: [],
      },
      // 表单参数
      form: {}
      ,
      //列信息
      columns: [
        {key: 0, label: "序号", visible: true},
        {key: 1, label: "封面图片", visible: true},
        {key: 2, label: "广告链接地址", visible: true},
        {key: 3, label: "广告简述", visible: true},
        {key: 4, label: "排序", visible: false},
        {key: 5, label: "状态", visible: true},
        {key: 6, label: "广告位置", visible: true},
        {key: 7, label: "备注", visible: true},
      ],
      // 表单校验
      rules: {
        imgSrc: [{
          required: true,
          message: "封面图片不能为空",
          trigger: "blur"
        }],
        url: [{
          required: true,
          message: "广告链接不能为空",
          trigger: "blur"
        }],
        sketch: [{
          required: true,
          message: "广告简述不能为空",
          trigger: "blur"
        }],
        dateRange: [{
          required: true,
          message: "展示周期不能为空",
          trigger: "blur"
        }],
        sort: [{
          required: true,
          message: "排序不能为空",
          trigger: "blur"
        }],
        status: [{
          required: true,
          message: "状态不能为空",
          trigger: "change"
        }],
        place: [{
          required: true,
          message: "广告位置不能为空",
          trigger: "change"
        }],
      }
    }

  },
  created() {
    this.getList()
    this.getDicts("t_advertisement_state").then(response => {
      this.statusOptions = response.data;
    })
    this.getDicts("t_advertisement_place").then(response => {
      this.placeOptions = response.data;
    })
  },
  methods: {
    /** 查询运营管理广告列表 */
    getList() {
      this.loading = true
      listAdvertisement(this.queryParams).then(response => {
        this.advertisementList = response.rows
        this.total = response.total
        this.loading = false
        for (let i in this.advertisementList) {
          this.srcList.push(this.advertisementList[i].imgSrc)
        }
      })

    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    //广告位置字典翻译
    placeFormat(row, column) {
      return this.selectDictLabel(this.placeOptions, row.place)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        advertisementId: null,
        imgSrc: null,
        url: null,
        sketch: null,
        sort: null,
        status: null,
        place: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        startTime: null,
        endTime: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.advertisementId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //上传图片
    getFile(file) {
      this.getBase64(file.raw).then(res => {
        this.form.imgSrc = res
      });
    },
    //将本地图片转成base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加运营管理广告'
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const advertisementId =
        row.advertisementId || this.ids
      getAdvertisement(advertisementId).then(response => {
        this.form = response.data
        this.form.dateRange = []
        this.form.dateRange.push(this.form.startTime)
        this.form.dateRange.push(this.form.endTime)
        this.open = true
        this.title = '修改运营管理广告'
        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        })
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
          if (valid) {
            this.form.startTime = this.form.dateRange[0]
            this.form.endTime = this.form.dateRange[1]
            if (this.form.advertisementId != null) {
              updateAdvertisement(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addAdvertisement(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        }
      )

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const advertisementIds = row.advertisementId || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        cancelButtonClass: 'btn-custom-cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(function () {
        return delAdvertisement(advertisementIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有运营管理广告数据项?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        closeOnClickModal: false,
        type: 'info'
      }).then(function () {
        return exportAdvertisement(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
